function getBrowserVersion () {
  const ua = navigator.userAgent || navigator.vendor || window.opera
  const uaInfo = {
    ios: /\(i[^]+( U)? CPU.+Mac OS X/i.test(ua),
    android: /Android/i.test(ua) || /Linux/i.test(ua)
  }
  return {
    isIos () {
      return uaInfo.ios
    },
    isAndroid () {
      return uaInfo.android
    }
  }
}

const browserVersion = getBrowserVersion()

// 注册事件监听，初始化(bridge===WebViewJavascriptBridge)
function setupWebViewJavascriptBridge (callback) {
  if (browserVersion.isIos()) {
    // IOS
    if (window.WebViewJavascriptBridge) {
      // eslint-disable-next-line no-undef
      return callback(WebViewJavascriptBridge)
    }
    if (window.WVJBCallbacks) {
      return window.WVJBCallbacks.push(callback)
    }
    window.WVJBCallbacks = [callback]
    const WVJBIframe = document.createElement('iframe')
    WVJBIframe.style.display = 'none'
    WVJBIframe.src = 'https://__bridge_loaded__'
    document.documentElement.appendChild(WVJBIframe)
    setTimeout(function () {
      document.documentElement.removeChild(WVJBIframe)
    }, 0)
  } else if (browserVersion.isAndroid()) {
    if (window.WebViewJavascriptBridge) {
      // eslint-disable-next-line no-undef
      callback(WebViewJavascriptBridge)
    } else {
      document.addEventListener(
        'WebViewJavascriptBridgeReady'
        , function () {
          // eslint-disable-next-line no-undef
          callback(WebViewJavascriptBridge)
        },
        false
      )
    }
  } else {
    // console.log('other navigator')
  }
}

export default {
  // {isIos(), isAndroid()}
  browserVersion,
  // web 调用 app
  webCallHandler (name, data, callback) {
    setupWebViewJavascriptBridge((bridge) => {
      bridge.callHandler(name, data, callback)
    })
  },
  // app 调用 web
  webRegisterHandler (name, callback) {
    setupWebViewJavascriptBridge((bridge) => {
      if (browserVersion.isAndroid()) {
        bridge.init((data, responseCallback) => { })
      }
      bridge.registerHandler(name, (data, responseCallback) => {
        callback(data, responseCallback)
      })
    })
  }
}
